package com.itheima.health.controller;


import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.OrderSettingService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/ordersetting")
@Slf4j
public class OrderSetController {

    @Autowired
    private OrderSettingService orderSettingService;

    /**
     * 文件上传
     *
     * @param excelFile
     * @return
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile excelFile) {
        log.info("[预约设置-文件上传]fileName:{},size:{}", excelFile.getOriginalFilename(), excelFile.getSize());
        String filename = excelFile.getOriginalFilename();
        if (StringUtils.isEmpty(filename)) {
            return new Result(false, "缺少文件名");
        }
        //1.抽取excel数据poi
        Workbook workbook = null;
        try (InputStream is = excelFile.getInputStream();) {
            //构造workbook
            if (filename.endsWith(".xls")) {
                workbook = new XSSFWorkbook(is);
            } else if (filename.endsWith(".xlsx")) {
                workbook = new XSSFWorkbook(is);
            } else {
                return new Result(false, "文件格式不对,请检查重试");
            }
        } catch (IOException e) {
            log.error("", e);
            return new Result(false, "文件上传失败");
        }
        //遍历取数据
        List<OrderSetting> orderSettings = new ArrayList<>();
        for (Sheet sheet : workbook) {
            //第0行为表头,直接从第一行获取
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                //获取行
                Row row = sheet.getRow(i);
                //解析行
                OrderSetting orderSetting = parseOrderSetting(row);
                //加入列表
                orderSettings.add(orderSetting);
            }
        }
        log.info("[预约设置-上传]解析成功,result:{}", orderSettings);

        //调用数据入库
        orderSettingService.addAll(orderSettings);
        return new Result(true, MessageConst.IMPORT_ORDERSETTING_SUCCESS);

    }

    /**
     * 从excel行提取OrderSetting数据
     *
     * @param row
     * @return
     */
    private OrderSetting parseOrderSetting(Row row) {
        Date date = null;
        Integer number = null;
        try {
            //获取日期
            if (null != row.getCell(0)) {
                //如果单元格没有数据，则getDateCellValue返回null
                date = row.getCell(0).getDateCellValue();
            }
            //获取最大预约数量
            if (null != row.getCell(1)) {
                //如果单元格没有数据，则getNumericCellValue返回0
                double numberValue = row.getCell(1).getNumericCellValue();
                //将double型转为int型
                number = Double.valueOf(numberValue).intValue();
            }
        } catch (IllegalStateException | NumberFormatException e) {
            log.error("", e);
            throw new BusinessRuntimeException(String.format("数据格式错误,%s 第%d行", row.getSheet().getSheetName(), row.getRowNum() + 1));
        }
        // 判断是否缺少数据
        if (null == date || null == number) {
            throw new BusinessRuntimeException(String.format("缺少必填数据,%s 第%d行", row.getSheet().getSheetName(), row.getRowNum() + 1));
        }
        return new OrderSetting(date, number);
    }


    /**
     * 根据年月查询数据
     */
    @GetMapping("/getOrderSettingByMonth")
    public Result getOrderSettingByMonth(@RequestParam Integer year, @RequestParam Integer month) {
        String date = year + "-" + month;
        try {
            List<Map<String, Integer>> list = orderSettingService.getOrderSettingByMonth(date);
            //获取预约设置数据成功
            return new Result(true, MessageConst.GET_ORDERSETTING_SUCCESS, list);
        } catch (Exception e) {
            e.printStackTrace();
            //获取预约设置数据失败
            return new Result(false, MessageConst.GET_ORDERSETTING_FAIL);
        }

    }

    /**
     *  根据指定日期修改可预约人数
     * @param orderSetting
     * @return
     */
    @PostMapping("/editNumberByDate")
    public Result editNumberByDate(@RequestBody OrderSetting orderSetting){
        try {
            orderSettingService.editNumberByDate(orderSetting);
            return new Result(true,MessageConst.ORDERSETTING_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.ORDERSETTING_FAIL);
        }
    }
}
